package cn.itheima.action;

import cn.itheima.domain.Standard;
import cn.itheima.service.StandardService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by millions on 2017/7/2.
 */

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard>{

    private Standard standard=new Standard();

    @Override
    public Standard getModel() {

        return standard;
    }

    @Autowired
    private StandardService standardService;

    @Action(value = "/standard_pageQuery",results = {@Result(type = "json")})
    public String standardQuery(){

        List<Standard> list=standardService.findAll();
        System.out.println(list);
        ActionContext.getContext().getValueStack().push(list);

        return SUCCESS;
    }

    @Action(value = "/standard_save",results = {@Result(name = "success",type = "redirect",location = "./pages/base/standard.html")})
    public String standardSave(){
        standardService.save(standard);
        return SUCCESS;
    }

    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Action(value = "/standard_queryByPage",results = {@Result(type = "json")})
    public String standardQueryByPage(){
        Pageable pageable = new PageRequest(page-1, rows);

        Page<Standard> pageData=standardService.findByPage(pageable);
        Map<String,Object> map=new HashMap<>();
        map.put("total",pageData.getTotalElements());
        map.put("rows",pageData.getContent());

        ActionContext.getContext().getValueStack().push(map);

        return SUCCESS;
    }
}
